package edu.chinasoft.handler;


import edu.chinasoft.domain.User;
import edu.chinasoft.exception.DispatcherServletException;
import edu.chinasoft.exception.HandlerException;
import edu.chinasoft.exception.MapperException;
import edu.chinasoft.exception.ServiceException;
import edu.chinasoft.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller("UserHandler")
@RequestMapping("/userHandler")
public class UserHandler extends DispatcherServletException {
    private Logger logger = LoggerFactory.getLogger(UserHandler.class);
    private UserService userService;

    //处理登录请求
    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    public void method01(HttpServletRequest request, HttpServletResponse response) {

        try {
            logger.debug("UserHandler>>>method01 start ……");

            //获取页面提交的内容
            String userName = request.getParameter("user_name");
            String userPassword = request.getParameter("user_password");


            //封装到javabean
            User user = new User();
            user.setUserName(userName);
            user.setUserPasswrod(userPassword);


            //调用服务层方法
            User userLogin = this.userService.loginUser(user);


            logger.debug("UserHandler>>>method01 end ……");
            if (null == userLogin) {
                //根据执行结果实现页面跳转
                response.sendRedirect("" + request.getContextPath() + "/login_fail.jsp");
            } else {
                //把登录的用户保存到域里
                HttpSession session = request.getSession();
                session.setAttribute("user", userLogin);

                //跳转到主页面
                response.sendRedirect("" + request.getContextPath() + "/main.jsp");

            }
        } catch (MapperException e) {
            throw e;
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            throw new HandlerException(e);
        }


    }


    public UserService getUserService() {
        return userService;
    }

    @Autowired
    @Qualifier(value = "userService")
    public void setUserService(UserService userService) {
        this.userService = userService;
    }




}
